package com.gmq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmq.common.CustomExcetion;
import com.gmq.common.R;
import com.gmq.dto.DishDto;
import com.gmq.dto.SetmealDto;
import com.gmq.entity.Category;
import com.gmq.entity.Dish;
import com.gmq.entity.Setmeal;
import com.gmq.entity.SetmealDish;
import com.gmq.service.CategoryService;
import com.gmq.service.DishService;
import com.gmq.service.SetmealDishService;
import com.gmq.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("查询套餐列表{},{},{}", page, pageSize, name);

        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件
        queryWrapper.like(name != null, Setmeal::getName, name);
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(setmealPage, queryWrapper);

        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");
        List<SetmealDto> setmealDtoList = new ArrayList<>();
        for (Setmeal record : setmealPage.getRecords()) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(record, setmealDto);
            //查询套餐分类名称
            Long categoryId = record.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            String name1 = byId.getName();
            setmealDto.setCategoryName(name1);
            setmealDtoList.add(setmealDto);
        }
        setmealDtoPage.setRecords(setmealDtoList);
        return R.success(setmealDtoPage);
    }

    @PostMapping("/status/{status}")
    @CacheEvict(cacheNames = "SetmealListCache", allEntries = true)
    public R<String> status(@PathVariable int status, Long[] ids) {
        log.info("修改{}套餐状态{}", ids, status);
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("修改成功");
    }

    @DeleteMapping
    @Transactional
    @CacheEvict(cacheNames = "SetmealListCache", allEntries = true)
    public R<String> delete(Long[] ids) {
        log.info("删除菜品{}", ids);
        for (Long id : ids) {
            Setmeal byId = setmealService.getById(id);
            if (byId.getStatus() == 1) {
                throw new CustomExcetion("无法删除还在售卖的套餐");
            }
            setmealService.removeById(id);
        }
        return R.success("删除成功");
    }

    @GetMapping("{id}")
    public R<SetmealDto> setmealItem(@PathVariable Long id) {
        log.info("查询套餐{}明细", id);
        SetmealDto setmealDto = new SetmealDto();
        Setmeal byId = setmealService.getById(id);
        BeanUtils.copyProperties(byId, setmealDto);
        //查询菜品
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(queryWrapper);
        setmealDto.setSetmealDishes(list);
        return R.success(setmealDto);
    }

    @PutMapping
    @Transactional
    @CacheEvict(cacheNames = "SetmealListCache", key = "#setmealDto.categoryId")
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        log.info("修改套餐{}", setmealDto);
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto, setmeal);
        setmealService.updateById(setmeal);
        //修改菜品
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(queryWrapper);
        for (SetmealDish setmealDish : setmealDto.getSetmealDishes()) {
            setmealDish.setSetmealId(setmeal.getId());
            setmealDishService.save(setmealDish);
        }
        return R.success("修改成功");
    }

    @PostMapping
    @Transactional
    @CacheEvict(cacheNames = "SetmealListCache", key = "#setmealDto.categoryId")
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("保存套餐", setmealDto);
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto, setmeal);
        setmealService.save(setmeal);
        for (SetmealDish setmealDish : setmealDto.getSetmealDishes()) {
            setmealDish.setSetmealId(setmeal.getId());
            setmealDishService.save(setmealDish);
        }
        return R.success("添加成功");
    }

    @GetMapping("/list")
    //当返回的结果不为空的时候再进行缓存
    //condition 满足条件缓存
    //unless 满足条件不缓存
    @Cacheable(cacheNames = "SetmealListCache", key = "#categoryId")
    public R<List<Setmeal>> list(Long categoryId) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Setmeal::getCategoryId, categoryId);
        queryWrapper.like(Setmeal::getStatus, 1);
        List<Setmeal> list1 = setmealService.list(queryWrapper);
        return R.success(list1);
    }

    @GetMapping("/dish/{id}")
    public R<List<DishDto>> setmealDish(@PathVariable Long id) {
        List<DishDto> dishDtos = new ArrayList<>();
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(SetmealDish::getSetmealId, id);
        List<SetmealDish> list = setmealDishService.list(queryWrapper);
        for (SetmealDish setmealDish : list) {
            DishDto dishDto = new DishDto();
            Dish byId = dishService.getById(setmealDish.getDishId());
            BeanUtils.copyProperties(byId, dishDto);
            dishDto.setCopies(setmealDish.getCopies());
            dishDtos.add(dishDto);
        }
        return R.success(dishDtos);
    }
}
